﻿using CPPEI.Coolzon.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using DT = CPPEI.Coolzon.Designtime.Metadata;

namespace CPPEI.Coolzon.DesignServer.Domain.Services
{
    public class ItemService
    {
        /// <summary>
        /// 签出项目
        /// 1.根据itemId获取item
        /// 2.需要把IsEditing设为true,把Editor设为签出者,更新Item
        /// 3.返回ServiceResult
        /// </summary>
        /// <param name="userIdentity">签出者</param>
        /// <param name="solutionId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public ServiceResult CheckOut(string userIdentity, Guid solutionId, Guid itemId, Guid WorkSpaceId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);

                Entities.Item oItem = rep.Get(p => p.Id == itemId && p.IsDeleted == false);
                if (oItem != null)
                {
                    if (oItem.IsEditing == false)
                    {
                        oItem.IsEditing = true;
                        oItem.Editor = userIdentity;
                        oItem.Updatedtime = DateTime.Now;
                        oItem.WorkSpaceId = WorkSpaceId;

                        rep.Update(oItem);

                        try
                        {
                            dbContext.SaveChanges();
                            Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}签出项目:{1}成功.", userIdentity, itemId));
                            return new ServiceResult(true, 0, string.Empty);
                        }
                        catch (Exception ex)
                        {
                            Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}签出项目:{1}失败.", userIdentity, itemId));
                            return new ServiceResult(false, 0, ex.Message);
                        }

                    }
                    else
                    {
                        Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}签出项目:{1}失败.", userIdentity, itemId));

                        return new ServiceResult(false, 0, string.Format("该项目被{0}占用，不能签出该项目", oItem.Editor));
                    }
                }
                Common.Logger.ErrorToTag("ItemService", string.Format("用户:{0}签出项目:{1}失败.", userIdentity, itemId));
                return new ServiceResult(false, 1, "项目签出失败");
            }
        }

        public SingleResult<Entities.Item> Undo(string userIdentity, Guid solutionId, Guid itemId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);

                Entities.Item oItem = rep.Get(p => p.Id == itemId && p.IsEditing == true );
                if (oItem != null)
                {
                    oItem.IsDeleted = false;
                    oItem.IsEditing = false;
                    oItem.Editor = null;

                    rep.Update(oItem);

                    if (dbContext.SaveChanges() > 0)
                    {
                        Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}撤销项目状态更改:{1}成功.", userIdentity, itemId));
                        return new SingleResult<Entities.Item>(true, 0, string.Empty, oItem);
                    }
                }
                Common.Logger.ErrorToTag("ItemService", string.Format("用户:{0}撤销项目状态更改:{1}失败.", userIdentity, itemId));
                return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
            }
        }

        /// <summary>
        /// 获取方案特定版本下所有项目
        /// </summary>
        /// <param name="solutionId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public ListResult<Entities.ItemHistory> GetSolutionItemListSV(Guid solutionId, int version)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.ItemHistory> rep = new Repositories.EntityRepository<Entities.ItemHistory>(dbContext);
                List<Entities.ItemHistory> list = rep.GetList(p => p.SolutionId == solutionId && p.ItemVersion == version);
                Common.Logger.InfoToTag("ItemService", string.Format("获取方案Id:{0}里所有的项目信息.", solutionId));
                return new ListResult<Entities.ItemHistory>(true, 0, string.Empty, list);
            }
        }

        /// <summary>
        /// 删除项目
        /// 1.根据itemId获取item
        /// 2.需要把IsDeleted设为true,把Editor设为签出者,更新Item
        /// 3.返回ServiceResult
        /// </summary>
        /// <param name="userIdentity">签出者</param>
        /// <param name="solutionId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public ServiceResult Delete(string userIdentity, Guid solutionId, Guid itemId, Guid WorkSpaceId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);

                Entities.Item oItem = rep.Get(p => p.Id == itemId && p.IsDeleted == false);
                if (oItem != null)
                {
                    if (oItem.IsEditing)
                    {
                        if (string.Equals(userIdentity, oItem.Editor) && int.Equals(WorkSpaceId, oItem.WorkSpaceId))
                        {
                            oItem.Status = Entities.ItemStatus.Delete;
                            oItem.Updatedtime = DateTime.Now;

                            rep.Update(oItem);

                            if (dbContext.SaveChanges() > 0)
                            {
                                Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}删除项目:{1}成功.", userIdentity, itemId));
                                return new ServiceResult(true, 0, string.Empty);
                            }
                        }
                        else
                        {
                            if (string.Equals(userIdentity, oItem.Editor))
                            {
                                Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}删除项目:{1}失败.", userIdentity, itemId));

                                return new ServiceResult(false, 0, string.Format("项目删除失败.该项目在其他工作空间被占用"));

                            }
                            else
                            {
                                Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}删除项目:{1}失败.", userIdentity, itemId));

                                return new ServiceResult(false, 0, string.Format("该项目被{0}占用，不能删除该项目", oItem.Editor));
                            }
                        }
                    }
                    else
                    {
                        oItem.IsEditing = true;
                        oItem.Status = Entities.ItemStatus.Delete;
                        oItem.Editor = userIdentity;
                        oItem.Updatedtime = DateTime.Now;
                        oItem.WorkSpaceId = WorkSpaceId;

                        rep.Update(oItem);

                        if (dbContext.SaveChanges() > 0)
                        {
                            Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}删除项目:{1}成功.", userIdentity, itemId));

                            return new ServiceResult(true, 0, string.Empty);
                        }
                    }
                }
                Common.Logger.ErrorToTag("ItemService", string.Format("用户:{0}删除项目:{1}失败.", userIdentity, itemId));
                return new ServiceResult(false, 1, "项目删除失败");
            }
        }


        /// <summary>
        /// 判断当前用户与签出者是不是同一人
        /// </summary>
        /// <param name="solutionId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public SingleResult<Entities.Item> IsDif(string userIdentity, Guid solutionId, Guid itemId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
              
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);
                Entities.Item oItem = rep.Get(p => p.SolutionId == solutionId && p.Id == itemId && p.Editor == userIdentity && p.IsEditing == true);
                if (oItem != null)
                {
                    oItem.IsEditing = false;
                    oItem.Editor = string.Empty;

                    rep.Update(oItem);
                    if (dbContext.SaveChanges() < 0)//失败
                    {
                        return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
                    }
                }
                return new SingleResult<Entities.Item>(true, 0, string.Empty, oItem);
            }
        }


        /// <summary>
        /// 签入新项目
        /// 1.根据itemId获取当前Item
        /// 2.如果当前item存在，则需要当前item存为ItemHistory
        /// 3.如果当前item不存在,则保存当前item（需要把IsEditing设为false,把Editor清空）,保存当前item
        /// 4.返回ServiceResult
        /// </summary>
        /// <param name="userIdentity">签入者</param>
        /// <param name="item"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public SingleResult<Entities.Item> CheckIn(string userIdentity, Entities.Item item, Stream stream)
        {
            if (item.Type == CPPEI.Coolzon.DesignServer.Domain.Models.Constant.ItemType.Folder)
            {
                return CheckInFolder(userIdentity, item, stream);
            }
            return CheckInFile(userIdentity, item, stream);
        }

        private SingleResult<Entities.Item> CheckInFile(string userIdentity, Entities.Item item, Stream stream)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);

                Entities.Item oItem = rep.Get(p => p.Id == item.Id);

                if (item.SolutionId == item.Id)
                {
                    ListResult<Entities.Item> list = GetDeletingList(item.SolutionId, item.Id);
                    for (int index = 0; index < list.Data.Count; index++)
                    {
                        CheckInDeleteItem(userIdentity, list.Data[index]);
                    }
                }

                string solutionDirectory = CPPEI.Coolzon.Designtime.Metadata.Storage.GetSolutionDirectory(item.SolutionId);
                string relativeHistoryFilePath = string.Empty;
                string filePath = null;

                #region step1:保存文件
                if (oItem != null)
                {
                    oItem.Version = oItem.Version + 1;
                    filePath = DT.Storage.GetItemFilePath(item.SolutionId, oItem.Path); ;

                    Common.Logger.InfoToTag(Library.LogTAG, string.Format("保存文件:{0}", filePath));
                    // 保存新的文件
                    if (DT.Storage.SaveItemFile(filePath, stream) == false)
                    {
                        return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
                    }

                    oItem.IsEditing = false;
                    oItem.Editor = string.Empty;

                    //如果该项标记为删除，则签入时，删除该条数据
                    if (oItem.Status == Entities.ItemStatus.Delete)
                    {
                        oItem.IsDeleted = true;
                    }
                    oItem.Status = Entities.ItemStatus.CheckIn;

                    rep.Update(oItem);
                   
                }
                else
                {
                    // 获取项目文件相对地址
                    filePath = CPPEI.Coolzon.Designtime.Metadata.Storage.GetItemFilePath(item.SolutionId, item.Id, item.Type);
                    string relativeFilePath = relativeHistoryFilePath = filePath.Replace(solutionDirectory, string.Empty);
                    oItem = item;

                    Common.Logger.InfoToTag(Library.LogTAG, string.Format("保存文件:{0}", filePath));
                    // 保存新的文件
                    if (DT.Storage.SaveItemFile(filePath, stream) == false)
                    {
                        return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
                    }

                    oItem.Path = relativeFilePath;
                    oItem.Status = Entities.ItemStatus.CheckIn;
                    rep.Create(oItem);
                }
                #endregion

                #region 生成备份
                // 备份已有的文件
                string historyFilePath = DT.Storage.GetItemFilePath(item.SolutionId, item.Id, item.Type, oItem.Version);
                relativeHistoryFilePath = historyFilePath.Replace(solutionDirectory, string.Empty);

                try
                {
                    // 备份文件已经存在，先删除掉，重新备份(一般不会出现)
                    if (File.Exists(historyFilePath))
                    {
                        Logger.WarningToTag(Library.LogTAG, string.Format("存在备份文件:{0}", historyFilePath));
                        File.Delete(historyFilePath);
                    }

                    if (File.Exists(filePath))
                    {
                        Common.Logger.InfoToTag(Library.LogTAG, string.Format("文件:{0}生成备份文件:{1}", filePath, historyFilePath));
                        //为当前文件备份历史文件记录
                        System.IO.File.Copy(filePath, historyFilePath);
                    }
                }
                catch (Exception ex)
                {
                    Common.Logger.ErrorToTag(Library.LogTAG, string.Format("用户:{0}签入新项目:{1}失败.ex:{2}", userIdentity, item.Id, ex));
                    return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
                }

                #endregion

                Entities.ItemHistory itemHistory = new Entities.ItemHistory();
                itemHistory.Id = Guid.NewGuid();
                itemHistory.ItemVersion = oItem.Version;
                itemHistory.ItemId = oItem.Id;
                itemHistory.ItemName = oItem.Name;
                itemHistory.ItemParentId = oItem.ParentId;
                itemHistory.ItemFolderId = oItem.FolderId;
                itemHistory.ItemPath = relativeHistoryFilePath;
                itemHistory.ItemType = oItem.Type;
                itemHistory.OperatedTime = oItem.Updatedtime;
                itemHistory.Operator = userIdentity;
                itemHistory.SolutionId = oItem.SolutionId;
                itemHistory.Action = Models.Constant.ActionType.CheckIn;

                Repositories.EntityRepository<Entities.ItemHistory> repItemHistory = new Repositories.EntityRepository<Entities.ItemHistory>(dbContext);
                repItemHistory.Create(itemHistory);

                try
                {
                    if (dbContext.SaveChanges() > 0)
                    {
                        Common.Logger.InfoToTag(Library.LogTAG, string.Format("用户:{0}签入新项目:{1}成功.", userIdentity, item.Id));
                        return new SingleResult<Entities.Item>(true, 0, string.Empty, oItem);
                    }
                }
                catch (Exception ex)
                {
                    Common.Logger.ErrorToTag(Library.LogTAG, string.Format("用户:{0}签入新项目:{1}失败.ex:{2}", userIdentity, item.Id, ex));
                }
                return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
            }
        }
        private SingleResult<Entities.Item> CheckInFolder(string userIdentity, Entities.Item item, Stream stream)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);

                Entities.Item oItem = rep.Get(p => p.Id == item.Id);
                if (oItem != null)
                {                  
                    oItem.IsEditing = false;
                    oItem.Editor = string.Empty;
                    oItem.Version = oItem.Version + 1;

                    //如果该项标记为删除，则签入时，删除该条数据
                    if (oItem.Status == Entities.ItemStatus.Delete)
                    {
                        oItem.IsDeleted = true;
                    }
                    oItem.Status = Entities.ItemStatus.CheckIn;

                    rep.Update(oItem);
                }
                else
                {
                    oItem = item;
                    oItem.Path = string.Empty;
                    oItem.Version = 1;
                    oItem.Status = Entities.ItemStatus.CheckIn;
                    rep.Create(oItem);
                }

                Entities.ItemHistory itemHistory = new Entities.ItemHistory();
                itemHistory.Id = Guid.NewGuid();
                itemHistory.ItemVersion = oItem.Version;
                itemHistory.ItemId = oItem.Id;
                itemHistory.ItemName = oItem.Name;
                itemHistory.ItemParentId = oItem.ParentId;
                itemHistory.ItemFolderId = oItem.FolderId;
                itemHistory.ItemPath = string.Empty;
                itemHistory.ItemType = oItem.Type;
                itemHistory.OperatedTime = oItem.Updatedtime;
                itemHistory.Operator = userIdentity;
                itemHistory.SolutionId = oItem.SolutionId;

                Repositories.EntityRepository<Entities.ItemHistory> repItemHistory = new Repositories.EntityRepository<Entities.ItemHistory>(dbContext);
                repItemHistory.Create(itemHistory);


                if (dbContext.SaveChanges() > 0)
                {
                    Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}签入新项目:{1}成功.", userIdentity, item.Id));
                    return new SingleResult<Entities.Item>(true, 0, string.Empty, oItem);
                }
                Common.Logger.ErrorToTag("ItemService", string.Format("用户:{0}签入新项目:{1}失败.", userIdentity, item.Id));
                return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
            }
        }

        private SingleResult<Entities.Item> CheckInDeleteItem(string userIdentity, Entities.Item item)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);

                Entities.Item oItem = rep.Get(p => p.Id == item.Id);
                if (oItem != null)
                {
                    oItem.IsEditing = false;
                    oItem.Editor = string.Empty;
                    oItem.Version = oItem.Version + 1;
                    oItem.IsDeleted = true;
                    oItem.Status = Entities.ItemStatus.CheckIn;

                    rep.Update(oItem);
                }
                else
                {
                    Common.Logger.ErrorToTag("ItemService", string.Format("用户:{0}签入删除项目:{1}失败.找不到要删除文件", userIdentity, item.Id));
                    return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
                }

                Entities.ItemHistory itemHistory = new Entities.ItemHistory();
                itemHistory.Id = Guid.NewGuid();
                itemHistory.ItemVersion = oItem.Version;
                itemHistory.ItemId = oItem.Id;
                itemHistory.ItemName = oItem.Name;
                itemHistory.ItemParentId = oItem.ParentId;
                itemHistory.ItemFolderId = oItem.FolderId;
                itemHistory.ItemPath = string.Empty;
                itemHistory.ItemType = oItem.Type;
                itemHistory.OperatedTime = oItem.Updatedtime;
                itemHistory.Operator = userIdentity;
                itemHistory.SolutionId = oItem.SolutionId;

                Repositories.EntityRepository<Entities.ItemHistory> repItemHistory = new Repositories.EntityRepository<Entities.ItemHistory>(dbContext);
                repItemHistory.Create(itemHistory);


                if (dbContext.SaveChanges() > 0)
                {
                    Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}签入新项目:{1}成功.", userIdentity, item.Id));
                    return new SingleResult<Entities.Item>(true, 0, string.Empty, oItem);
                }
                Common.Logger.ErrorToTag("ItemService", string.Format("用户:{0}签入新项目:{1}失败.", userIdentity, item.Id));
                return new SingleResult<Entities.Item>(false, 1, string.Empty, null);
            }
        }

        /// <summary>
        /// 获取项目的历史记录
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public ListResult<Entities.ItemHistory> GetHistories(Guid itemId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.ItemHistory> rep = new Repositories.EntityRepository<Entities.ItemHistory>(dbContext);
                List<Entities.ItemHistory> list = rep.GetList(p => p.ItemId == itemId,p=>p.ItemVersion);
                Common.Logger.InfoToTag("ItemService", string.Format("获取项目Id:{0}的历史记录成功.", itemId));
                return new ListResult<Entities.ItemHistory>(true, 0, string.Empty, list);
            }
        }

        /// <summary>
        /// 获取要删除项目的历史记录
        /// </summary>
        /// <param name="itemId"></param>
        /// <returns></returns>

        public ListResult<Entities.Item> GetDeletingList(Guid solutionId, Guid itemId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);
                List<Entities.Item> items = new List<Entities.Item>();
                if (solutionId == itemId)
                {
                    items = rep.GetList(p => p.SolutionId == solutionId && p.Status == Entities.ItemStatus.Delete && p.IsEditing == true);
                    return new ListResult<Entities.Item>(true, 0, string.Empty, items);
                }
                Entities.Item item = rep.Get(p => p.SolutionId == solutionId && p.Id == itemId && p.IsEditing == true);
                if (item == null)
                {
                    return new ListResult<Entities.Item>(true, 0, string.Empty, items);
                }
                //items.Add(item);
                List<Entities.Item> folderItems;
                if (item.Type == CPPEI.Coolzon.DesignServer.Domain.Models.Constant.ItemType.Folder)
                {
                    folderItems = rep.GetList(p => p.SolutionId == solutionId && p.Status == Entities.ItemStatus.Delete && p.FolderId == item.Id && p.IsEditing == true);
                    foreach (var folderItem in folderItems)
                    {
                        items.AddRange(GetFolderChildren(rep, folderItem, solutionId));
                    }
                }
                else
                {
                    folderItems = rep.GetList(p => p.SolutionId == solutionId && p.Status == Entities.ItemStatus.Delete && p.ParentId == item.Id && p.IsEditing == true);
                    foreach (var folderItem in folderItems)
                    {
                        items.AddRange(GetChildren(rep, folderItem, solutionId));
                    }
                }
                items.AddRange(folderItems);
                Common.Logger.InfoToTag("ItemService", string.Format("根据solutionId:{0},itemId:{1},获取要删除项目", solutionId, itemId));
                return new ListResult<Entities.Item>(true, 0, string.Empty, items);
            }
        }

        /// <summary>
        /// 获取方案里所有的项目信息，不包含已经被删除的项目
        /// </summary>
        /// <param name="solutionId">方案Id</param>
        /// <returns></returns>
        public ListResult<Entities.Item> GetItems(Guid solutionId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);
                List<Entities.Item> list = rep.GetList(p => p.SolutionId == solutionId && p.IsDeleted != true);
                Common.Logger.InfoToTag("ItemService", string.Format("获取方案Id:{0}里所有的项目信息，不包含已经被删除的项目成功.", solutionId));
                return new ListResult<Entities.Item>(true, 0, string.Empty, list);
            }
        }

        /// <summary>
        /// 获取项目
        /// </summary>
        /// <param name="solutionId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public SingleResult<Entities.Item> GetItem(Guid solutionId, Guid itemId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);
                Entities.Item item = rep.Get(p => p.SolutionId == solutionId && p.Id == itemId && p.IsDeleted != true);
                Common.Logger.InfoToTag("ItemService", string.Format("根据solutionId:{0},获取项目成功,itemId:{1}.", solutionId, itemId));
                return new SingleResult<Entities.Item>(true, 0, string.Empty, item);
            }
        }

        /// <summary>
        /// 获取项目
        /// </summary>
        /// <param name="solutionId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public SingleResult<Entities.ItemHistory> GetItemHistory(Guid solutionId, Guid itemId,int version, string userIdentity)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.ItemHistory> rep = new Repositories.EntityRepository<Entities.ItemHistory>(dbContext);
                var historyItem = rep.Get(p => p.SolutionId == solutionId && p.ItemId == itemId && p.ItemVersion==version);
                if (historyItem != null)
                {
                    Repositories.EntityRepository<Entities.Item> repItem = new Repositories.EntityRepository<Entities.Item>(dbContext);
                    Entities.Item item = repItem.Get(p => p.SolutionId == solutionId && p.Id == itemId && p.IsDeleted != true);
                    if(item != null)
                    {
                        if (string.Equals(userIdentity, item.Editor))
                        {
                            item.IsEditing = false;
                            item.Editor = null;
                            repItem.Update(item);
                            if (dbContext.SaveChanges() > 0)
                            {
                                Common.Logger.InfoToTag("ItemService", string.Format("获取特定版本，更新项目编辑状态:{0} 成功.", itemId));
                            }
                            else
                            {
                                Common.Logger.ErrorToTag("ItemService", string.Format("获取特定版本，更新项目编辑状态:{0} 失败.", itemId));
                            }
                        }
                    }
                    Common.Logger.InfoToTag("ItemService", string.Format("根据solutionId:{0},获取项目成功,itemId:{1}.", solutionId, itemId));
                    return new SingleResult<Entities.ItemHistory>(true, 0, string.Empty, historyItem);
                }
                return new SingleResult<Entities.ItemHistory>(true, 0, string.Empty, null);
            }
        }

      
        public ListResult<Entities.Item> GetItemChildren(Guid solutionId, Guid itemId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);
                List<Entities.Item> items = new List<Entities.Item>();
                if (solutionId == itemId)
                {
                    items = rep.GetList(p => p.SolutionId == solutionId && p.IsDeleted != true);
                    return new ListResult<Entities.Item>(true, 0, string.Empty, items);
                }
                Entities.Item item = rep.Get(p => p.SolutionId == solutionId && p.IsDeleted != true && p.Id == itemId);
                if(item == null)
                {
                    return new ListResult<Entities.Item>(true, 0, string.Empty, items);
                }
                items.Add(item);
                List<Entities.Item> folderItems;
                if (item.Type == CPPEI.Coolzon.DesignServer.Domain.Models.Constant.ItemType.Folder)
                {
                    folderItems = rep.GetList(p => p.SolutionId == solutionId && p.IsDeleted != true && p.FolderId == item.Id);
                    foreach (var folderItem in folderItems)
                    {
                        items.AddRange(GetFolderChildren(rep, folderItem, solutionId));
                    }
                }
                else
                {
                    folderItems = rep.GetList(p => p.SolutionId == solutionId && p.IsDeleted != true && p.ParentId == item.Id);
                    foreach (var folderItem in folderItems)
                    {
                        items.AddRange(GetChildren(rep, folderItem, solutionId));
                    }
                }
                items.AddRange(folderItems);
                Common.Logger.InfoToTag("ItemService", string.Format("根据solutionId:{0},itemId:{1},获取子项目", solutionId, itemId));
                return new ListResult<Entities.Item>(true, 0, string.Empty, items);
            }
        }
        private List<Entities.Item> GetFolderChildren(Repositories.EntityRepository<Entities.Item> rep, Entities.Item item, Guid solutionId)
        {
            List<Entities.Item> children = new List<Entities.Item>();
            List<Entities.Item> folderItems = new List<Entities.Item>();
            if (item.Type == CPPEI.Coolzon.DesignServer.Domain.Models.Constant.ItemType.Folder)
            {
                folderItems = rep.GetList(p => p.SolutionId == solutionId && p.IsDeleted != true && p.FolderId == item.Id);
                foreach (var folderItem in folderItems)
                {
                    children.AddRange(GetFolderChildren(rep, folderItem, solutionId));
                }
            }
            children.AddRange(folderItems);
            return children;
        }
        private List<Entities.Item> GetChildren(Repositories.EntityRepository<Entities.Item> rep, Entities.Item item, Guid solutionId)
        {
            List<Entities.Item> children = new List<Entities.Item>();
            List<Entities.Item> folderItems = new List<Entities.Item>();
            if (item.Type == CPPEI.Coolzon.DesignServer.Domain.Models.Constant.ItemType.Folder)
            {
                folderItems = rep.GetList(p => p.SolutionId == solutionId && p.IsDeleted != true && p.FolderId == item.Id);
                foreach (var folderItem in folderItems)
                {
                    children.AddRange(GetFolderChildren(rep, folderItem, solutionId));
                }
            }
            else
            {
                folderItems = rep.GetList(p => p.SolutionId == solutionId && p.IsDeleted != true && p.ParentId == item.Id);
                foreach (var folderItem in folderItems)
                {
                    children.AddRange(GetChildren(rep, folderItem, solutionId));
                }
            }
            children.AddRange(folderItems);
            return children;
        }

        public ServiceResult DeleteItem(string userIdentity, Guid solutionId, Guid itemId)
        {
            using (DSDBContext dbContext = new DSDBContext())
            {
                Repositories.EntityRepository<Entities.Item> rep = new Repositories.EntityRepository<Entities.Item>(dbContext);

                Entities.Item oItem = rep.Get(p => p.Id == itemId && p.IsDeleted == false && p.IsEditing == true);
                if (oItem != null)
                {
                    oItem.IsDeleted = true;
                    oItem.Updatedtime = DateTime.Now;

                    rep.Update(oItem);

                    if (dbContext.SaveChanges() > 0)
                    {
                        Common.Logger.InfoToTag("ItemService", string.Format("用户:{0}删除项目:{1}成功.", userIdentity, itemId));
                        return new ServiceResult(true, 0, string.Empty);
                    }
                }
                Common.Logger.ErrorToTag("ItemService", string.Format("用户:{0}删除项目:{1}失败.", userIdentity, itemId));
                return new ServiceResult(false, 1, string.Empty);
            }
        }
    }
}
